package com.unlcn.ils.wms.web.controller.stock;

import cn.huiyunche.commons.domain.ResultDTO;
import cn.huiyunche.commons.exception.BusinessException;
import com.alibaba.fastjson.JSONObject;
import com.unlcn.ils.wms.backend.bo.inboundBO.WmsInboundAllocationBO;
import com.unlcn.ils.wms.backend.enums.WarehouseEnum;
import com.unlcn.ils.wms.backend.service.inbound.WmsAllocationService;
import com.unlcn.ils.wms.backend.service.inbound.WmsInventoryService;
import com.unlcn.ils.wms.backend.util.BrowerEncodeingUtils;
import com.unlcn.ils.wms.base.businessDTO.stock.WmsInventoryQueryDTO;
import com.unlcn.ils.wms.base.dto.WmsInventoryChangeLocCodeDTO;
import com.unlcn.ils.wms.base.dto.WmsInventoryFreezeDTO;
import com.unlcn.ils.wms.base.model.stock.WmsInventoryLocation;
import com.unlcn.ils.wms.web.controller.inbound.WmsInboundOrderController;
import com.unlcn.ils.wms.web.vo.inbound.WmsInboundAllocationVO;
import com.unlcn.ils.wms.web.vo.stock.WmsInventoryVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

/**
 * wms库存管理
 * Created by DELL on 2017/8/7.
 */
@Controller
@RequestMapping("/wmsInventory")
@ResponseBody
public class WmsInventoryController {

    private Logger logger = LoggerFactory.getLogger(WmsInboundOrderController.class);

    @Autowired
    private WmsInventoryService wmsInventoryService;

    @Autowired
    private WmsAllocationService wmsAllocationService;

    /**
     * 库存查询
     * <p>
     * 2018-1-23
     * 库存查询页面增加“物料代码”、“物料名称”、“颜色代码”、“颜色”字段显示，导出的文件中也需要包含这四个字段
     * 查询条件中增加“物料名称”、“颜色”、“库存状态”
     * </p>
     *
     * @param dto 参数封装
     * @return 返回值
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public ResultDTO list(@RequestBody WmsInventoryQueryDTO dto, HttpServletRequest request) {
        logger.info("WmsInventoryController.list param:{}.", dto);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "查询成功");
        try {
            String whCode = request.getHeader("whCode");
            if (StringUtils.isBlank(whCode)) {
                return resultDTO;
            }
            dto.setInvWhCode(whCode);
            if (WarehouseEnum.UNLCN_XN_CQ.getWhCode().equals(whCode)) {
                resultDTO.setData(wmsInventoryService.queryListByInventory(dto));
            } else if (WarehouseEnum.JM_CS.getWhCode().equals(whCode) || WarehouseEnum.JM_XY.getWhCode().equals(whCode)) {
                resultDTO.setData(wmsInventoryService.queryInventoryListForJunMa(dto));
            }
        } catch (BusinessException e) {
            logger.error("WmsInventoryController.list error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(e.getMessage());
        } catch (Exception e) {
            logger.error("WmsInventoryController.list error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("查询异常");
        }
        return resultDTO;
    }

    /**
     * 冻结车辆信息
     *
     * @param freezeDTO 参数封装
     * @return 返回值
     */
    @RequestMapping(value = "/stockFreeze", method = RequestMethod.POST)
    public ResultDTO<Object> updateStockFreeze(@RequestBody WmsInventoryFreezeDTO freezeDTO, HttpServletRequest request) {
        logger.debug("WmsInventoryController.updateStockFreeze params:{}", freezeDTO);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "操作成功!");
        try {
            String whCode = request.getHeader("whCode");
            freezeDTO.setWhCode(whCode);
            wmsInventoryService.updateStockFreeze(freezeDTO);
        } catch (BusinessException e) {
            logger.error("WmsInventoryController.updateStockFreeze BusinessException:", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(e.getMessage());
        } catch (Exception ex) {
            logger.error("WmsInventoryController.updateStockFreeze error:", ex);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("操作失败!");
        }
        return resultDTO;
    }

    /**
     * 解冻车辆信息
     *
     * @param freezeDTO 参数封装
     * @return 返回值
     */
    @RequestMapping(value = "/stockNormal", method = RequestMethod.POST)
    public ResultDTO<Object> updateStockNormal(@RequestBody WmsInventoryFreezeDTO freezeDTO, HttpServletRequest request) {
        logger.debug("WmsInventoryController.updateStockNormal params:{}", freezeDTO);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "操作成功!");
        try {
            String whCode = request.getHeader("whCode");
            freezeDTO.setWhCode(whCode);
            wmsInventoryService.updateStockNormal(freezeDTO);
        } catch (BusinessException e) {
            logger.error("WmsInventoryController.updateStockNormal BusinessException:", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(e.getMessage());
        } catch (Exception ex) {
            logger.error("WmsInventoryController.updateStockNormal error:", ex);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("操作失败!");
        }
        return resultDTO;
    }

    /**
     * 解冻车辆信息
     *
     * @param dto 参数封装
     * @return 返回值
     */
    @RequestMapping(value = "/changeLocCode", method = RequestMethod.POST)
    public ResultDTO<Object> updateChangeLocCode(@RequestBody WmsInventoryChangeLocCodeDTO dto, HttpServletRequest request) {
        logger.debug("WmsInventoryController.updateChangeLocCode params:{}", dto);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "替换成功!");
        try {
            String whCode = request.getHeader("whCode");
            dto.setWhCode(whCode);
            wmsInventoryService.updateChangeLocCode(dto);
        } catch (BusinessException e) {
            logger.error("WmsInventoryController.updateChangeLocCode BusinessException:", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(e.getMessage());
        } catch (Exception ex) {
            logger.error("WmsInventoryController.updateChangeLocCode error:", ex);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("替换失败!");
        }
        return resultDTO;
    }

    @RequestMapping("/colourList")
    public ResultDTO<Object> listAllColour(@RequestBody WmsInventoryVO wmsInventoryVO, HttpServletRequest request) throws BusinessException {
        logger.info("WmsInventoryController.listAllColour param:{}.");
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "查询成功");
        try {
            WmsInventoryQueryDTO wmsInventoryQueryDTO = new WmsInventoryQueryDTO();
            BeanUtils.copyProperties(wmsInventoryVO, wmsInventoryQueryDTO);
            String whCode = request.getHeader("whCode");
            wmsInventoryQueryDTO.setInvWhCode(whCode);
            resultDTO.setData(wmsInventoryService.selectColourListForJM(wmsInventoryQueryDTO));
        } catch (BusinessException e) {
            logger.error("WmsInventoryController.listAllColour error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(e.getMessage());
        } catch (Exception e) {
            logger.error("WmsInventoryController.listAllColour error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("查询异常");
        }
        return resultDTO;
    }

    @RequestMapping("/materialList")
    public ResultDTO<Object> listAllMaterial(@RequestBody WmsInventoryVO wmsInventoryVO, HttpServletRequest request) throws BusinessException {
        logger.info("WmsInventoryController.materialList param:{}.", JSONObject.toJSONString(wmsInventoryVO));
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "查询成功");
        try {
            WmsInventoryQueryDTO wmsInventoryQueryDTO = new WmsInventoryQueryDTO();
            BeanUtils.copyProperties(wmsInventoryVO, wmsInventoryQueryDTO);
            String whCode = request.getHeader("whCode");
            wmsInventoryQueryDTO.setInvWhCode(whCode);
            resultDTO.setData(wmsInventoryService.selectMaterialListForJM(wmsInventoryQueryDTO));
        } catch (BusinessException e) {
            logger.error("WmsInventoryController.listAllMaterial error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(e.getMessage());
        } catch (Exception e) {
            logger.error("WmsInventoryController.listAllMaterial error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("查询异常");
        }
        return resultDTO;
    }


    @RequestMapping("/listInventoryLocation/{invId}")
    public ResultDTO<Object> listInventoryLocation(@PathVariable("invId") String invId) throws BusinessException {
        if (StringUtils.isBlank(invId)) {
            logger.info("WmsInventoryController.listInventoryLocation param:{}.", invId);
        }
        ResultDTO<Object> resultDTO = new ResultDTO<Object>(true, null, "查询成功");
        try {
            List<WmsInventoryLocation> wmsInventoryLocationList = wmsInventoryService.listInventoryLocation(invId);
            resultDTO.setData(wmsInventoryLocationList);
            resultDTO.setSuccess(true);
        } catch (Exception e) {
            logger.error("WmsInventoryController.list error: {}", e);
            resultDTO.setMessage("查询异常");
            //throw new BusinessException("查询异常");
        }
        return resultDTO;
    }

    @RequestMapping(value = "/stockMoveRecord", method = RequestMethod.POST)
    public ResultDTO<Object> stockMoveRecord(@RequestBody WmsInboundAllocationVO wmsInboundAllocationVO) {
        ResultDTO<Object> resultDTO = new ResultDTO<>();
        try {
            WmsInboundAllocationBO wmsInboundAllocationBO = new WmsInboundAllocationBO();
            BeanUtils.copyProperties(wmsInboundAllocationVO, wmsInboundAllocationBO);
            Map<String, Object> result = wmsAllocationService.selectStockMoveRecord(wmsInboundAllocationBO);
            resultDTO.setData(result);
            resultDTO.setSuccess(true);
            resultDTO.setMessage("查询成功");
            return resultDTO;
        } catch (Exception ex) {
            resultDTO.setSuccess(false);
            resultDTO.setMessage("查询失败");
            return resultDTO;
        }
    }

    /**
     * 库存记录导出
     * <p>
     * 2018-1-23
     * 库存查询页面增加“物料代码”、“物料名称”、“颜色代码”、“颜色”字段显示，导出的文件中也需要包含这四个字段
     * 查询条件中增加“物料名称”、“颜色”、“库存状态”
     * </p>
     *
     * @param request  请求
     * @param response 响应
     * @return 返回值
     */
    @RequestMapping(value = "/inventoryRecordImport", method = RequestMethod.GET)
    public ResultDTO<Object> inventoryRecordImport(String whCode, HttpServletRequest request, HttpServletResponse response) {
        logger.info("WmsInventoryController.inventoryRecordImport");
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "库存导出成功");
        OutputStream outputStream = null;
        HSSFWorkbook workbook = null;
        try {
            //String whCode = request.getHeader("whCode");
            if (StringUtils.isBlank(whCode)) {
                resultDTO.setSuccess(false);
                resultDTO.setMessage("当前登录用户未绑定仓库");
                return resultDTO;
            }
            WmsInventoryQueryDTO wmsInventoryQueryDTO = new WmsInventoryQueryDTO();
            wmsInventoryQueryDTO.setInvWhCode(whCode);
            if (WarehouseEnum.UNLCN_XN_CQ.getWhCode().equals(whCode)) {
                //西南库存数据导出
                workbook = wmsInventoryService.inventoryRecordImportForCq(wmsInventoryQueryDTO);
            } else if (WarehouseEnum.JM_CS.getWhCode().equals(whCode) || WarehouseEnum.JM_XY.getWhCode().equals(whCode)) {
                //君马库存数据导出
                workbook = wmsInventoryService.inventoryRecordImportForJm(wmsInventoryQueryDTO);
            }
            if (workbook != null) {
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/vnd.ms-excel;charset=UTF-8");
                response.setHeader("Content-disposition", BrowerEncodeingUtils.getContentDisposition("InventoryRecordImportExcel.xls", request));
                outputStream = response.getOutputStream();
                workbook.write(outputStream);
                outputStream.flush();
            }
        } catch (BusinessException e) {
            logger.info("WmsInventoryController.inventoryRecordImport businessException: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(e.getMessage());
        } catch (Exception e) {
            logger.info("WmsInventoryController.inventoryRecordImport error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("库存导出失败");
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
                if (workbook != null) {
                    workbook.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultDTO;
    }


    /**
     * 库存导出数据判断
     *
     * @param whCode 仓库code
     * @return 返回值
     */
    @RequestMapping(value = "/queryInventoryRecordCount", method = RequestMethod.GET)
    public ResultDTO<Object> queryInventoryRecordCount(String whCode) {
        logger.info("WmsInventoryController.queryInventoryRecordCount");
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "查询成功");
        try {
            if (StringUtils.isBlank(whCode)) {
                resultDTO.setSuccess(false);
                resultDTO.setMessage("当前登录用户未绑定仓库");
                return resultDTO;
            }
            WmsInventoryQueryDTO wmsInventoryQueryDTO = new WmsInventoryQueryDTO();
            wmsInventoryQueryDTO.setInvWhCode(whCode);
            Integer integer = wmsInventoryService.countInventoryRecord(wmsInventoryQueryDTO);
            //Integer integer = wmsInventoryService.countInventoryRecordWithNotice(wmsInventoryQueryDTO);
            if (integer == null || integer <= 0) {
                resultDTO.setSuccess(false);
                resultDTO.setMessage("没有对应的数据");
                return resultDTO;
            }
        } catch (BusinessException e) {
            logger.info("WmsInventoryController.queryInventoryRecordCount businessException: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(e.getMessage());
        } catch (Exception e) {
            logger.info("WmsInventoryController.queryInventoryRecordCount error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("库存导出失败");
        }
        return resultDTO;
    }
}
